package com.fengycx.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fengycx.constants.Constants;
import com.fengycx.pojo.domain.DriverSetting;
import com.fengycx.mapper.DriverSettingMapper;
import com.fengycx.pojo.dto.DriverPositionDto;
import com.fengycx.service.IDriverSettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengycx.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 司机配置 服务实现类
 * </p>
 *
 * @author Cino
 * @since 2024-02-19
 */
@Service
public class DriverSettingServiceImpl extends ServiceImpl<DriverSettingMapper, DriverSetting> implements IDriverSettingService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 司机上线
     */
    @Override
    public void driverOnline() {
        long driverId = StpUtil.getLoginIdAsLong();
        DriverSetting driverSetting = super.getById(driverId);
        AssertUtil.isNotNull(driverSetting,"查询对象不存在！");
        //把司机设置以JSON格式存入Redis
        JSONObject driverSettingObj = JSONUtil.toBean(JSONUtil.toJsonStr(driverSetting), JSONObject.class);

        String key = String.format(Constants.Redis.DRIVER_ONLINE_KEY, driverId);
        redisTemplate.opsForValue().set(key,driverSettingObj,8, TimeUnit.HOURS);

    }

    /**
     * 司机下线
     */
    @Override
    public void driverOffline() {
        //删除司机redis信息
        long driverId = StpUtil.getLoginIdAsLong();
        String key = String.format(Constants.Redis.DRIVER_ONLINE_KEY, driverId);
        redisTemplate.delete(key);

        //删除司机 geo（经纬度）信息，仅删除当前司机下的geo信息
        redisTemplate.opsForGeo().remove(Constants.Redis.DRIVER_LOCATION_KEY,String.valueOf(driverId));

    }

    /**
     * 将司机实时位置缓存进Redis
     * @param positionDto
     */
    @Override
    public void SyncDriverPosition(DriverPositionDto positionDto) {
        String driverId = StpUtil.getLoginIdAsString();
        redisTemplate.opsForGeo().add(Constants.Redis.DRIVER_LOCATION_KEY
                ,new Point(Double.parseDouble(positionDto.getLongitude()),Double.parseDouble(positionDto.getLatitude()))
                ,driverId);

    }
}
